﻿using System.Windows.Forms;
using System.Data;
using ClassMetadataBrowser.Domain;
using System.Collections.Generic;
using System;
using System.Drawing;
using Gl.SettingsManager;
using ClassMedataBrowser.Domain;

namespace ClassMetadataBrowser.ToolControls
{
	public partial class MembersList : UserControl, IConsumerForm
	{
		[SettingProperty]
		public string SearchCriteria
		{
			get;
			set;
		}

		[SettingProperty]
		public int NameColumnWidth
		{
			get;
			set;
		}

		#region Members

		private readonly DataTable _contents;
		private readonly Dictionary<int, MetadataObjectBase> _metadataMap;

		#endregion

		#region Properties

		public IHost HostWindow
		{
			get;
			set;
		}

		public Button OkButton
		{
			get { return _btnOk; }
		}

		public Button CancelButton
		{
			get { return _btnCancel; }
		}

		#endregion

		public MembersList()
		{
			InitializeComponent();
			Initialize();

			_contents = new DataTable();

			_contents.Columns.Add(new DataColumn("Id", typeof(int)));
			_contents.Columns.Add(new DataColumn("MemberIcon", typeof(Bitmap)));
			_contents.Columns.Add(new DataColumn("MemberName"));

			_gridViewMembers.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			_metadataMap = new Dictionary<int, MetadataObjectBase>();
		}

		private void Initialize()
		{
			_gridViewMembers.CellDoubleClick += new DataGridViewCellEventHandler(CellDoubleClick);
			_gridViewMembers.ColumnWidthChanged += new DataGridViewColumnEventHandler(ColumnWidthChanged);
		}

		private void ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
		{
			if (e.Column.Name == _memberName.Name)
			{
				NameColumnWidth = e.Column.Width;
			}
		}

		private void CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			SelectCurrent(true);
		}

		public void Bind(IMetadataProvider provider)
		{
			_contents.Clear();
			_metadataMap.Clear();

			MetadataImage image = new MetadataImage();
			int currentId = 0;
			foreach (MetadataObjectBase mob in provider.Metadata)
			{
				currentId++;
				mob.Accept(image);
				image.Icon.MakeTransparent(image.Icon.GetPixel(0, 0));
				_contents.Rows.Add(currentId, image.Icon, mob.Name);
				_metadataMap.Add(currentId, mob);
			}

			BindGrid();
		}

		private void BindGrid()
		{
			_gridViewMembers.DataSource = _contents;
		}

		private void CriteriaTextChanged(object sender, EventArgs e)
		{
			_contents.DefaultView.RowFilter = string.Format("MemberName like '%{0}%'", _txtCriteria.Text);
			SearchCriteria = _txtCriteria.Text;
		}

		protected override bool ProcessKeyPreview(ref Message m)
		{
			if (m.Msg == Utils.KeyDownConst)
				switch (m.WParam.ToInt32())
				{
					case 38:
						_gridViewMembers.ChangeRow(true);
						return true;
					case 40:
						_gridViewMembers.ChangeRow(false);
						return true;
				}

			return base.ProcessKeyPreview(ref m);
		}

		internal void Clear() { }

		private void CriteriaKeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == 13)
			{
				SelectCurrent(true);
				e.Handled = true;
			}
		}

		public void SelectCurrent(bool closeWindow)
		{
			if (_gridViewMembers.SelectedCells.Count > 0)
			{
				DataRowView row = (DataRowView)_gridViewMembers.Rows[_gridViewMembers.SelectedCells[0].RowIndex].DataBoundItem;
				MetadataObjectBase mob = _metadataMap[(int)row["Id"]];
				mob.Navigate();
				if (closeWindow)
				{
					FindForm().DialogResult = DialogResult.OK;
					FindForm().Close();
				}
			}
		}

		protected override void OnLoad(EventArgs e)
		{
			// loading settings
			Settings.GetSettingsWithRegistryProvider().Load(this);
			base.OnLoad(e);

			if (NameColumnWidth > 0)
				_gridViewMembers.Columns[2].Width = NameColumnWidth;

			if (!string.IsNullOrEmpty(SearchCriteria))
				_txtCriteria.Text = SearchCriteria;
		}

		protected override void OnLostFocus(EventArgs e)
		{
			// saving settings
			base.OnLostFocus(e);
		}

		public void SaveSettings()
		{
			Settings.GetSettingsWithRegistryProvider().Save(this);
		}

		public void SetFocusOnCriteria()
		{
			_txtCriteria.Focus();
			_txtCriteria.Select();
			ActiveControl = _txtCriteria;
		}

		public void AcceptColumnDescriptor(ColumnsDescriptor descriptor)
		{
			
		}
	}
}
